package phoenics.manpads.common.auth;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import phoenics.manpads.common.utils.JacksonUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * 自定义UsernamePasswordAnthenticationFilter
 *
 * @author Phoenics Chow
 * on 2018年12月15日
 */
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MyAuthenticationFilter.class);
    private AuthenticationBean authenticationBean=new  AuthenticationBean(null,null);
    @Override
    protected String obtainPassword(HttpServletRequest request) {
        takeAuthenticationBean(request);
        String password=this.authenticationBean.getPassword();
        this.authenticationBean.setPassword(null);
        return password;

    }
    @Override
    protected String obtainUsername(HttpServletRequest request) {
        takeAuthenticationBean(request);
        String name=this.authenticationBean.getUsername();
        this.authenticationBean.setUsername(null);
        return name;

    }

    private void takeAuthenticationBean(HttpServletRequest request){
        String name=this.authenticationBean.getUsername();
        String password=this.authenticationBean.getPassword();

        try {
            if(name==null && password==null){
                this.authenticationBean = JacksonUtil.readValue(request.getInputStream(),AuthenticationBean.class);
            }

        }catch (Exception e) {
            this.authenticationBean =new  AuthenticationBean("","") ;
        }
    }



}
